
import requests
from bs4 import BeautifulSoup 
def baidu_search(keyword):    
    # 设置请求头部信息，模拟浏览器访问    
    headers = {        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36'    }     
    # 构建搜索URL    
    search_url = f"https://www.baidu.com/s?wd={keyword}"     
    # 发送GET请求    
    response = requests.get(search_url, headers=headers)     
    # 检查请求是否成功    
    if response.status_code == 200:        
        # 解析响应内容        
        soup = BeautifulSoup(response.text, 'html.parser')
        # 查找搜索结果的标题和链接        
        search_results = soup.find_all('div', class_='c-container')         
        # 提取标题和链接        
        results = []        
        for result in search_results:            
            title = result.get_text()            
            link = result.a['href']            
            results.append({'title': title, 'link': link})         
            return results    
    else:        
        print("请求失败！")        
        return None 
# 测试爬虫功能
keyword = "音乐"
search_results = baidu_search(keyword)
if search_results:    
    print(f"关键字 '{keyword}' 的搜索结果：",len(search_results))  
    for idx, result in enumerate(search_results, 0):        
        print(f"{idx}. {result['title']}")        
        print(f"链接: {result['link']}")        
else:    
    print("未能获取搜索结果。")